﻿Imports System
Imports System.IO
Imports System.Net
Imports System.Text

Namespace Seuss.EnterpriseLibrary.Web.Utilities
    ''' <summary>
    ''' Provides convenience methods for issuing a HTTP "POST" command and returning the results.
    ''' </summary>
    Public Class WebUtility

        Public Shared Function DoHttpPost(ByVal targetUrl As String, ByVal postBody As String) As HttpWebResponse
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(targetUrl), HttpWebRequest)

            request.Method = "POST"

            Dim encoding__1 As Encoding = Encoding.GetEncoding("ISO-8859-1")

            Dim postBuffer As Byte() = encoding__1.GetBytes(postBody)

            request.ContentLength = postBuffer.Length
            request.ContentType = "application/x-www-form-urlencoded"

            Using requestStream As Stream = request.GetRequestStream()
                requestStream.Write(postBuffer, 0, postBuffer.Length)
            End Using

            Dim response As HttpWebResponse

            Try
                response = DirectCast(request.GetResponse(), HttpWebResponse)
            Catch we As WebException
                response = DirectCast(we.Response, HttpWebResponse)
            End Try

            Return response
        End Function

        Public Shared Sub DoHttpPost(ByVal targetUrl As String, ByVal postBody As String, ByRef resultCode As HttpStatusCode, ByRef resultBody As String)
            Dim response As HttpWebResponse = DoHttpPost(targetUrl, postBody)
            Try
                Using reader As New StreamReader(response.GetResponseStream())
                    resultCode = response.StatusCode
                    resultBody = reader.ReadToEnd()
                End Using
            Catch ex As Exception
                resultBody = "<html></html>"
            End Try
        End Sub
    End Class

End Namespace